package cn.edu.hbwe.book.servlet.user;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hbwe.book.entity.User;


import cn.edu.hbwe.book.service.user.UserService;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.获取登录页面的用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//2.调用service来判断用户名和密码是否正确
		UserService service = new UserService();
		User user;
		try {
			//System.out.println("test");
			user = service.login(username,password);
			if (user == null) {
				response.sendRedirect(request.getContextPath() + "/client/error.jsp");
				return;
			}
			if (user.getState() == 1) {//如果用户的状态为激活，才允许登录
				request.getSession().setAttribute("user", user);
				//用户为超级管理员则跳转到后台界面
				String role = user.getRole();
				if (role.equals("超级用户")) {
					response.sendRedirect(request.getContextPath() + "/admin/login/home.jsp");
					return;
				} else {
					response.sendRedirect(request.getContextPath() + "/client/myAccount.jsp");
					return;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			//request.setAttribute("register message", e.getMessage());
			//request.getRequestDispatcher("/client/login.jsp").forward(request, response);
			response.sendRedirect(request.getContextPath() + "/client/myAccount.jsp");
		
	}
}
